/*
 * @Author: wangtao
 * @Date: 2020-12-18 14:27:12
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-06-10 15:02:57
 * @Description: 合同签订
 */
import React, { Component, Fragment } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  PixelRatio,
  NativeModules,
  BackHandler
} from 'react-native';
import Orientation from 'react-native-orientation-locker';
import {
  fontColorBlack,
  fontColorLightGray,
  isAndroid,
  mainBgColorWhite,
  px2dp,
  splitLineColorLightGray,
} from '@/styles';
import { BackImage, Button, msg, Loading } from '@/common';
import { SignatureCapture } from '@/components';
import api from '@/api';
import { uploadImage } from '@/config';
import OrientationTips from './components/orientation-tips';

const { Submit } = Button;

export default class ContractAutograph extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showAutograph: false,
      isDragged: false,
      isLoading: false
    };
  }

  componentDidMount() {
    if (isAndroid) {
      this.listener = BackHandler.addEventListener(
        'hardwareBackPress',
        this._onBack,
      );
    }
  }

  componentWillUnmount() {
    this.listener && this.listener.remove();
  }

  render() {
    const { showAutograph, isDragged, isLoading } = this.state;
    if (!showAutograph) {
      return <OrientationTips setShowAutograph={this.setShowAutograph} />;
    }
    return (
      <>
        {
          isLoading ?
            <Loading text='正在签署...' /> :
            <View style={styles.container}>
              <View style={styles.header}>
                <TouchableOpacity
                  style={styles.back}
                  onPress={this.goBack}
                >
                  <BackImage />
                </TouchableOpacity>
                <Text style={styles.title}>您的签名</Text>
                <View style={styles.headerRight}>
                  <Submit
                    text='清空'
                    boxStyle={{
                      width: px2dp(100),
                      height: px2dp(62),
                      borderRadius: px2dp(8),
                      overflow: 'hidden',
                      backgroundColor: mainBgColorWhite,
                      borderWidth: 1 / PixelRatio.get(),
                      borderColor: splitLineColorLightGray,
                    }}
                    btnStyle={{}}
                    btnTextStyle={{
                      fontSize: px2dp(32),
                      color: fontColorLightGray,
                    }}
                    onClick={() => {
                      this.setState({
                        isDragged: false
                      });
                      this.refs.sign.resetImage();
                    }}
                  />
                  <Submit
                    text='确定'
                    boxStyle={{
                      width: px2dp(100),
                      height: px2dp(62),
                      borderRadius: px2dp(8),
                      overflow: 'hidden',
                    }}
                    btnStyle={{}}
                    btnTextStyle={{
                      fontSize: px2dp(32),
                    }}
                    onClick={() => {
                      this.saveSign();
                    }}
                  />
                </View>
              </View>
              <View style={styles.signatureWrap}>
                <SignatureCapture
                  style={[{ flex: 1 }, styles.signature]}
                  ref='sign'
                  onSaveEvent={this._onSaveEvent}
                  onDragEvent={this._onDragEvent}
                  saveImageFileInExtStorage
                  showNativeButtons={false}
                  showTitleLabel={false}
                  maxSize={100}
                />
              </View>
              <Text style={styles.tipsText}>
                请在框内手写签名
                {!isDragged && <Text style={styles.warnTips}>（您还未签名）</Text>}
              </Text>

            </View>
        }
      </>
    );
  }

  _onBack = () => {
    if (isAndroid) {
      Orientation.lockToPortrait();
    } else {
      NativeModules.BridgeManager.iosLockToPortrait();
    }
  }

  // 触发_onSaveEvent方法
  saveSign = () => {
    let { isDragged } = this.state;
    if (!isDragged) {
      msg.emit('app:tip', { text: '请签名' });
      return false;
    }
    // 旋转为竖屏
    if (isAndroid) {
      Orientation.lockToPortrait();
    } else {
      NativeModules.BridgeManager.iosLockToLandscape(false);
    }
    this.refs.sign.saveImage();
  }

  // 展示签名
  setShowAutograph = () => {
    this.setState({ showAutograph: true });
    // 旋转为横屏
    if (isAndroid) {
      Orientation.lockToLandscape();
    } else {
      NativeModules.BridgeManager.iosLockToLandscape(true);
    }
  };

  // 返回
  goBack = () => {
    msg.emit('router: back');
    // 旋转为竖屏
    if (isAndroid) {
      Orientation.lockToPortrait();
    } else {
      NativeModules.BridgeManager.iosLockToLandscape(false);
    }
  };

  _onSaveEvent = (result) => {
    if (isAndroid) {
      Orientation.lockToPortrait();
    } else {
      NativeModules.BridgeManager.iosLockToPortrait();
    }
    this.setState({ isLoading: true });
    // result.encoded - for the base64 encoded png
    // result.pathName - for the file path name
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { instId, routerFrom, data } = params;
    // 上传图片得到oss
    const $imgUri = isAndroid ? `file://${result.pathName}` : result.pathName;
    uploadImage('upload?dirName=contract', $imgUri)
      .then((res) => {
        console.log(`uploadImage：${JSON.stringify(res)}`);
        // 请求成功
        if (res.success) {
          if (routerFrom == 'B2BMallOrderPay') {
            // b2b 上传合同
            const contractParams = {
              instId: data.instanceId,
              refId: data.buyerId,
              refType: data.buyerType,
              remarkBase: result.encoded,
              remarkUrl: res.data.url,
            };
            api.contract.b2bSignPersonContract(contractParams).then(res => {
              this.setState({ isLoading: false });
              if (res.success) {
                const newData = Object.assign(res.data, data);
                msg.emit('router: goToNext', {
                  routeName: 'ContractFeedBack',
                  data: newData,
                  routerFrom
                });
              } else {
                this.setState({ showAutograph: false });
                msg.emit('app:tip', { text: res.msg });
              }
            }).catch(res => {
              this.setState({ isLoading: false });
              msg.emit('app:tip', { text: '网络错误' });
            });
          } else {
            let params = {
              instId,
              remarkBase: result.encoded,
              remarkUrl: res.data.url,
            };
            api.contract.signPersonContract(params).then(resData => {
              this.setState({ isLoading: false });
              if (!resData.success) {
                msg.emit('app:tip', { text: resData.msg });
                // if (isAndroid) {
                //   Orientation.lockToLandscape();
                // } else {
                //   NativeModules.BridgeManager.iosLockToLandscape();
                // }
                this.setState({ showAutograph: false });
                return;
              }
              console.log('==签订成功==', resData);
              let mergeData = resData.data;
              const newData = Object.assign(mergeData, data);
              msg.emit('router: goToNext', {
                routeName: 'ContractFeedBack',
                data: newData,
                routerFrom
              });
            }).catch(() => {
              msg.emit('app:tip', { text: '合同签订失败' });
              this.setState({ isLoading: false });
              // if (isAndroid) {
              //   Orientation.lockToLandscape();
              // } else {
              //   NativeModules.BridgeManager.iosLockToLandscape();
              // }
              this.setState({ showAutograph: false });
            });
          }
        } else {
          msg.emit('app:tip', { text: '图片上传失败' });
          this.setState({ showAutograph: false });
          // if (isAndroid) {
          //   Orientation.lockToLandscape();
          // } else {
          //   NativeModules.BridgeManager.iosLockToLandscape();
          // }
        }
      });
  }

  _onDragEvent = () => {
    let { isDragged } = this.state;
    if (isDragged == false) {
      this.setState({
        isDragged: true
      });
    }
    console.log('dragged');
  }
}
const styles = StyleSheet.create({
  container: {
    backgroundColor: mainBgColorWhite,
    width: '100%',
    height: '100%',
  },
  header: {
    width: '100%',
    height: px2dp(88),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: px2dp(36),
    fontWeight: 'bold',
    color: fontColorBlack,
  },
  back: {
    position: 'absolute',
    left: px2dp(32),
  },
  headerRight: {
    position: 'absolute',
    right: px2dp(32),
    width: px2dp(454),
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  signatureWrap: {
    flex: 1,
    borderColor: splitLineColorLightGray,
    borderWidth: 1,
    marginHorizontal: px2dp(32),
  },
  signature: {
    flex: 1,
  },
  tipsText: {
    textAlign: 'center',
    lineHeight: px2dp(68),
    fontSize: px2dp(32),
    color: fontColorLightGray
  },
  warnTips: {
    color: 'red'
  }
});
